<?php

namespace app\service;

use think\facade\Cache;
use think\facade\Request;

/**
 * API缓存服务类
 * 提供高性能的API响应缓存
 */
class CacheService
{
    /**
     * 生成缓存键
     */
    public static function getCacheKey(string $prefix, array $params = []): string
    {
        // 按模块、控制器、方法分组
        $module = Request::module() ?: 'index';
        $controller = Request::controller();
        $action = Request::action();

        // 基础键
        $baseKey = "{$prefix}:{$module}:{$controller}:{$action}";

        // 添加用户相关参数
        $userId = Request::param('user_id');
        if ($userId) {
            $baseKey .= ":user_{$userId}";
        }

        // 添加关键筛选参数
        $sortParams = ['keyword', 'status', 'level', 'department_id', 'type'];
        foreach ($sortParams as $param) {
            $value = Request::param($param);
            if ($value !== null && $value !== '') {
                $baseKey .= ":{$param}_{$value}";
            }
        }

        return md5($baseKey);
    }

    /**
     * 获取缓存
     */
    public static function get(string $key, $default = null)
    {
        $data = Cache::get($key);
        return $data !== false ? $data : $default;
    }

    /**
     * 设置缓存
     */
    public static function set(string $key, $value, int $ttl = 300): bool
    {
        return Cache::set($key, $value, $ttl);
    }

    /**
     * 缓存查询结果
     */
    public static function remember(string $key, callable $callback, int $ttl = 300)
    {
        $data = self::get($key);
        if ($data === null) {
            $data = $callback();
            self::set($key, $data, $ttl);
        }
        return $data;
    }

    /**
     * 删除缓存
     */
    public static function forget(string $key): bool
    {
        return Cache::delete($key);
    }

    /**
     * 清空模块缓存
     */
    public static function clearModule(string $module): bool
    {
        $keys = Cache::getTagKeys($module);
        if ($keys) {
            return Cache::delete($keys);
        }
        return true;
    }

    /**
     * 智能缓存策略
     */
    public static function smartCache(string $prefix, callable $callback, array $options = [])
    {
        $ttl = $options['ttl'] ?? 300; // 默认5分钟
        $useCache = $options['use_cache'] ?? true;

        // 缓存键生成
        $key = self::getCacheKey($prefix);

        // 检查缓存（仅GET请求且启用缓存）
        if ($useCache && Request::method() === 'GET') {
            $data = self::get($key);
            if ($data !== null) {
                return [
                    'data' => $data,
                    'cached' => true,
                    'cache_key' => $key
                ];
            }
        }

        // 执行查询
        $data = $callback();

        // 缓存结果
        if ($useCache && Request::method() === 'GET' && !empty($data)) {
            self::set($key, $data, $ttl);
        }

        return [
            'data' => $data,
            'cached' => false,
            'cache_key' => $key,
            'ttl' => $ttl
        ];
    }
}
